var config       = require('../config')
var javascripts  = require('../javascript-config.js')
var stylesheets    = require('../stylesheet-config.js')
var gulp         = require('gulp')
var path         = require('path')
var watch        = require('gulp-watch')


var watchTask = function() {

    // 普通任务
    var normalTasks = []

    // js
    if (global.jsTaskNameArray != "" && global.jsTaskObj != "") {
      var moduleName = '';
      global.jsTaskNameArray.forEach(function(moduleTask) {
        moduleName = moduleTask.split('_')[1];
        for (var i in javascripts.module) {
          if (i == moduleName) {
            javascripts.module[i].paths.forEach(function(pathName) {
              var glob = path.join(pathName)
              watchJs(glob,i);
              function watchJs(glob,i) {
                watch(glob, function() {
                  console.log(glob)
                  require('./js')['js_'+i]();
                }) 
              }          
            })
          }
        }
      });  
    }

    // css
    if (global.cssTaskNameArray != "" && global.cssTaskObj != "") {
      var moduleName = '';
      global.cssTaskNameArray.forEach(function(moduleTask) {
        moduleName = moduleTask.split('_')[1];
        for (var i in stylesheets.module) {
          if (i == moduleName) {
            stylesheets.module[i].paths.forEach(function(pathName) {
              var glob = path.join(pathName)
              watchCss(glob,i);
              function watchCss(glob,i) {
                watch(glob, function() {
                  require('./css')['css_'+i]();
                }) 
              }          
            })
          }
        }
      });  
    }

    // 普通
    if(normalTasks != "") {
      normalTasks.forEach(function(taskName) {
        var task = config.tasks[taskName]
        if (task) {
          var glob = path.join(config.root.src, task.src, '**/*.{' + task.extensions.join(',') + '}')
          watch(glob, function(event) {
           require('./' + taskName)()
          })
        }
      })  
    }

}

gulp.task('watch', watchTask)
module.exports = watchTask